<template>
    <div>
      <Tree
        v-model:expandedKeys="expandedKeys"
        v-model:selectedKeys="selectedKeys"
        :show-line="true"
        :show-icon="true"
        :load-data="handleLoadData"
        :tree-data="treeData"
        :fieldNames="fieldNames"
        @select="handleSelect"
      >
        <!-- 自定义节点标题 -->
        <template #title="{ key: treeKey, title, dataRef }">
          <Dropdown :trigger="['contextmenu']">
            <template v-if="dataRef.type === 'table' || dataRef.type === 'field'">
              <template v-if="dataRef.comment && dataRef.comment.length > 0">
                <Tooltip placement="right">
                  <template #title>{{ dataRef.comment }}</template>
                  <span>{{ title }}</span>
                </Tooltip>
              </template>
              <template v-else>
                <span>{{ title }}</span>
              </template>
            </template>
            <template v-else>
              <span>{{ title }}</span>
            </template>
  
            <!-- 右键菜单 -->
            <template #overlay>
              <template v-if="dataRef.type === 'database'">
                <Menu @click="({ key: menuKey }) => emitContextMenu(treeKey, 'database', title, menuKey, dataRef)">
                  <MenuItem key="NEW_QUERY">新建查询</MenuItem>
                  <MenuItem key="COPY_DATABASE_NAME">复制名称</MenuItem>
                  <MenuItem key="REFRESH_DATABASE">刷新</MenuItem>
                </Menu>
              </template>
              <template v-else-if="dataRef.type === 'tables'">
                <Menu @click="({ key: menuKey }) => emitContextMenu(treeKey, 'tables', title, menuKey, dataRef)">
                  <MenuItem key="NEW_QUERY">新建查询</MenuItem>
                  <MenuItem key="VIEW_ALL_TABLE">查看所有表</MenuItem>
                  <MenuItem key="NEW_TABLE">新建表</MenuItem>
                  <MenuItem key="REFRESH_TABLE">刷新</MenuItem>
                </Menu>
              </template>
              <template v-else-if="dataRef.type === 'table'">
                <Menu @click="({ key: menuKey }) => emitContextMenu(treeKey, 'table', title, menuKey, dataRef)">
                  <MenuItem key="OPEN_TABLE">打开表</MenuItem>
                  <MenuItem key="NEW_QUERY">新建查询</MenuItem>
                  <MenuItem key="VIEW_TABLE_DDL">查看DDL</MenuItem>
                  <MenuItem key="UPDATE_TABLE">修改表</MenuItem>
                  <MenuItem key="COPY_TABLE_NAME">复制名称</MenuItem>
                  <MenuItem key="REFRESH_TABLE">刷新</MenuItem>
                  <MenuItem key="DELETE_TABLE">删除表</MenuItem>
                </Menu>
              </template>
              <template v-else-if="dataRef.type === 'field'">
                <Menu @click="({ key: menuKey }) => emitContextMenu(treeKey, 'field', title, menuKey, dataRef)">
                  <MenuItem key="NEW_QUERY">新建查询</MenuItem>
                  <MenuItem key="COPY_FIELD_NAME">复制名称</MenuItem>
                  <MenuItem key="REFRESH_FIELD">刷新</MenuItem>
                </Menu>
              </template>
            </template>
          </Dropdown>
        </template>
        <!-- 自定义图标 -->
        <template #icon="{ dataRef }">
          <DatabaseOutlined v-if="dataRef.type === 'database'" />
          <FolderOutlined v-else-if="dataRef.type === 'tables'" />
          <TableOutlined v-else-if="dataRef.type === 'table'" />
        </template>
      </Tree>
    </div>
  </template>
  
  <script setup>
  import { ref, watch, defineEmits } from 'vue';
  import { Tree, Menu, MenuItem, Dropdown, Tooltip } from 'ant-design-vue';
  import { DatabaseOutlined, FolderOutlined, TableOutlined } from '@ant-design/icons-vue';
  
  // Props
  const props = defineProps({
    databases: {
      type: Array,
      required: true,
      default: () => [],
    },
    onDatabaseAction: {
      type: Function, // 自动补全接口方法
      required: true,
    },
  });
  
  // Emits
  const emit = defineEmits(['onLoadData', 'onContextMenuClick', 'onDatabaseSelect']);
  
  // States
  const expandedKeys = ref([]);
  const selectedKeys = ref([]);
  const treeData = ref([]);
  
  // Field names for the tree
  const fieldNames = ref({
    title: 'title',
    key: 'key',
    type: 'type',
    children: 'children',
  });
  
  // Initialize tree data
  watch(
    () => props.databases,
    (newDatabases) => {
      treeData.value = newDatabases.map((db) => ({
        title: db.name,
        key: db.name,
        type: 'database',
        isLeaf: false,
        children: [],
      }));
    },
    { immediate: true }
  );
  
  // Handle loading data
  const handleLoadData = async (treeNode, refresh) => {
    console.log("handleLoadData, treeNode:", treeNode);
    const { key, dataRef } = treeNode;
    if (!dataRef.children) {
      dataRef.children = [];
    }

    if (dataRef.type === 'database' && (refresh || dataRef.children.length === 0)) {
      const tables = await props.onDatabaseAction("getTables", {database: dataRef.title});
      console.log("getTableList, tables:", tables);
      if (tables && tables.length > 0) {
        tables.forEach((table) => {
          table.key = `${dataRef.title}-${table.key}`;
          table.database = dataRef.title;
          table.isLeaf = false;
          table.children = [];
        });
      }
      dataRef.children = [
        {
          title: 'tables',
          key: `${key}-tables`,
          type: 'tables',
          isLeaf: false,
          children: tables,
        },
      ];
      treeData.value = [...treeData.value];
    } else if (dataRef.type === 'table' && (refresh || dataRef.children.length === 0)) {
      const fields = await props.onDatabaseAction("getFields", {database: dataRef.database, table: dataRef.title});
      if (fields && fields.length > 0) {
        fields.forEach((field) => {
          field.key = `${key}-${dataRef.title}-${field.key}`;
          field.isLeaf = true;
        });
      }
      dataRef.children = fields;
      treeData.value = [...treeData.value];
    }
    return Promise.resolve();
  };


  // Handle node select events
  const handleSelect = (selectedKeys, { node }) => {
    console.log("handleSelect, selectedKeys:", selectedKeys, node);
    if (node.dataRef.type === 'database') {
      emit('onDatabaseSelect', { database: node.dataRef.database, type: node.dataRef.type, name: node.dataRef.title, node: node.dataRef });
    }   else if (node.dataRef.type === 'table') {
      emit('onTableSelect', { database: node.dataRef.database, type: node.dataRef.type, name: node.dataRef.title, node: node.dataRef });
    }
  };

  // Emit context menu click events
  const emitContextMenu = async (key, type, name, menuKey, data) => {
    console.log("emitContextMenu, key:", key, type, name, menuKey, data);
    if (menuKey === 'DELETE_TABLE') {
      await props.onDatabaseAction(menuKey, {database: data.database, table: data.name});

      // 获取当前key数据库节点，并刷新数据库表
      const databaseNode = treeData.value.find((node) => node.type === 'database' && node.title === data.database);
      console.log("databaseNode:", databaseNode, treeData.value);
      if (databaseNode) {
        await handleLoadData({key: databaseNode.key, dataRef: databaseNode}, true);
      }
    } else if (menuKey === 'CREATE_TABLE') {
      await props.onDatabaseAction(menuKey, {database: data.database});
    } else if (menuKey === 'UPDATE_TABLE') {
      await props.onDatabaseAction(menuKey, {database: data.database, table: data.name});
    } else if (menuKey === 'DELETE_FIELD') {
      await props.onDatabaseAction(menuKey, {database: data.database, table: data.table, field: data.name});
    }
  };

  </script>
  